﻿using System;
using System.Collections.Generic;

namespace Jayden.Dll.Core.Persistence.Data
{
	public class DbConnectionManager : IDisposable
	{
		private Configuration m_Configuration;

		public DbConnectionManager(Configuration config)
		{
			if (config == null)
				throw new ArgumentNullException("config");
			m_Configuration = config;
		}

		private Dictionary<string, DbConnectionProxy> m_Connections = new Dictionary<string, DbConnectionProxy>();
		public DbConnectionProxy GetConnection(string ldsn)
		{
			DbConnectionProxy proxy = null;
			if (!m_Connections.TryGetValue(ldsn, out proxy))
			{
				proxy = NewConnection(ldsn);
				m_Connections.Add(ldsn, proxy);
			}
			return proxy;
		}
		private DbConnectionProxy NewConnection(string ldsn)
		{
			string xpath = string.Format("Connection[@ldsn=\"{0}\"]", ldsn);
			Configuration config = m_Configuration.GetConfiguration(xpath);
			if (config == null)
				throw new Exception(string.Format("Unknow ldsn:'{0}'.", ldsn));
			string proxyType = config.GetValue("@proxyType", "Jayden.Dll.Core.Persistence.Data.DbConnectionProxy");
			string connectionType = config.GetValue("@type");
			string connectionString = config.GetValue("@connectionString");
			Type proxy = Type.GetType(proxyType);
			Type connection = Type.GetType(connectionType, true);
			DbConnectionProxy cProxy = Activator.CreateInstance(proxy, connection, connectionString) as DbConnectionProxy;
			return cProxy;
		}


		public void Dispose()
		{
			if (m_Connections != null)
				foreach (KeyValuePair<string, DbConnectionProxy> pair in m_Connections)
					if (pair.Value != null)
						pair.Value.Dispose();
			m_Connections = null;
		}
	}
}
